package org.geekbang.time.mathbasicthought.lesson7_permutate;

import java.util.Arrays;
import java.util.List;

/**
 * 假设有一个4位字母密码，每位密码是a~e之间的小写字母。你能否编写一段代码，来暴力破解该密码。
 * （提示:根据可重复排列的规律，生成所有可能的4位密码）
 */
public class PasswordCracking {

    public static List<String> targetPwdList = Arrays.asList("abcd");

    public static List<Character> limitedChar = Arrays.asList('a', 'b', 'c', 'd', 'e');

    public static void main(String[] args) {

        int digits = 4;
        for (String s : targetPwdList) {
            System.out.println("--------------破解密码：" + s + "-----------");
            permutate("", digits, s);
        }
    }

    public static void permutate(String result, int digits, String target) {
        if (digits == 0) {
            System.out.println("result:" + result);
            compare(result, target);
            System.out.println();
            return;
        }

        for (int i = 0; i < limitedChar.size(); i++) {
            String newResult = new String(result);
            newResult += limitedChar.get(i);

            permutate(newResult, digits - 1, target);
        }
    }

    private static void compare(String password, String target) {
        if (password.equals(target)) {
            System.out.println("密码匹配！");
        } else {
            System.out.println("密码不匹配！");
        }
    }

}
